package com.demo.intercepter;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.demo.core.constants.HttpStatus;
import com.demo.core.domain.Result;
import com.demo.utils.Token;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.LinkedHashMap;
import java.util.Map;

//拦截器
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
//        //HttpServletRequest:获取用户提交来的数据
//        if (request.getMethod().equals("OPTIONS")) {//获取方法GET/POST
//            response.setStatus(HttpServletResponse.SC_OK);
//            return true;
//        }
//        response.setCharacterEncoding("UTF-8");
//        //获取请求头中的令牌 前端vue将token添加在请求头中
//        String token = request.getHeader("token");
//        String message = "请先登录！";
//        try {
//            if (token != null) {
//                Token.verify(token);
//                System.out.println("通过拦截器");
                return true;
//            }
//            response.setCharacterEncoding("UTF-8");
//            response.setContentType("application/json;charset=utf-8");
//            System.out.println("认证失败，未通过拦截器");
//        } catch (SignatureVerificationException e) {
//            e.printStackTrace();
//            message = "无效签名";
//        } catch (TokenExpiredException e) {
//            e.printStackTrace();
//            message = "token过期";
//        } catch (AlgorithmMismatchException e) {
//            e.printStackTrace();
//            message = "token算法不一致！";
//        } catch (Exception e) {
//            e.printStackTrace();
//            message = "token无效！";
//        }
//        //将map转为json
//        Result result = new Result<>(HttpStatus.NOT_FOUND, message);
//        String json = new ObjectMapper().writeValueAsString(result);
//        response.setContentType("application/json;charset=UTF-8");
//        response.getWriter().println(json);
//        return false;
    }
}
